import { NextResponse } from 'next/server';
import { PrismaClient, GameMode } from '@prisma/client';

const prisma = new PrismaClient();

// 分数映射表（根据游戏模式计算分数）
const TIER_SCORE_MAP = {
  1: 100, // Tier 1
  2: 80,  // Tier 2
  3: 60,  // Tier 3
  4: 40,  // Tier 4
  5: 20   // Tier 5
};

// 模式基础分
const MODE_SCORE_MAP = {
  'SWORD': 100,
  'CRYSTAL': 90,
  'BUHC': 85,
  'POTION': 80,
  'NPOT': 75,
  'SMP': 70
};

// 比赛记录分数映射
const SCORE_MAP = {
  'HT1': 40, // 高阶Tier 1，最高分
  'LT1': 35, // 低阶Tier 1
  'HT2': 30, // 高阶Tier 2
  'LT2': 25, // 低阶Tier 2
  'HT3': 20, // 高阶Tier 3
  'LT3': 15, // 低阶Tier 3
  'HT4': 10, // 高阶Tier 4
  'LT4': 5,  // 低阶Tier 4
  'HT5': 3,  // 高阶Tier 5
  'LT5': 1,  // 低阶Tier 5
  'SWORD': 0, 'CRYSTAL': 0, 'BUHC': 0, 'POTION': 0, 'NPOT': 0, 'SMP': 0
};

// 获取玩家特定模式的段位
function getPlayerTier(player: any, mode: string): number | null {
  const tierMap: Record<string, keyof typeof player> = {
    'SWORD': 'swordTier',
    'CRYSTAL': 'crystalTier',
    'BUHC': 'buhcTier',
    'POTION': 'potionTier',
    'NPOT': 'npotTier',
    'SMP': 'smpTier'
  };
  
  const tierKey = tierMap[mode];
  return tierKey ? player[tierKey] : null;
}

// 根据数值段位获取段位名称
function getTierName(tierValue: number | null): string {
  if (tierValue === null) return '无等级';
  
  const TIER_NAMES: Record<number, string> = {
    1: 'HT1',
    2: 'LT1',
    3: 'HT2',
    4: 'LT2',
    5: 'HT3',
    6: 'LT3',
    7: 'HT4',
    8: 'LT4',
    9: 'HT5',
    10: 'LT5'
  };
  
  return TIER_NAMES[tierValue] || '无等级';
}

// 计算玩家段位总分
function calculateTierScore(player: any): number {
  let totalTierScore = 0;
  const modes = ['SWORD', 'CRYSTAL', 'BUHC', 'POTION', 'NPOT', 'SMP'];
  
  modes.forEach(mode => {
    const tierValue = getPlayerTier(player, mode);
    if (tierValue !== null) {
      // 获取段位名称
      const tierName = getTierName(tierValue);
      // 根据段位名称查找分数
      const tierScore = SCORE_MAP[tierName as keyof typeof SCORE_MAP] || 0;
      // 累加到总分
      totalTierScore += tierScore;
    }
  });
  
  return totalTierScore;
}

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const mode = searchParams.get('mode');
    
    // 获取所有玩家和他们的分数
    const players = await prisma.player.findMany({
      include: { scores: true }
    });
    
    // 如果指定了模式，则按该模式排序
    if (mode && Object.keys(GameMode).includes(mode)) {
      const specificMode = mode as GameMode;
      
      // 计算每个玩家在特定模式下的总分
      const rankings = players.map(player => {
        // 过滤出特定模式的分数
        const modeScores = player.scores.filter(score => score.mode === specificMode);
        const matchScoreTotal = modeScores.reduce((sum, score) => sum + score.value, 0);
        
        // 获取段位分数
        const tierValue = getPlayerTier(player, specificMode);
        let tierScore = 0;
        let tierName = '';
        
        if (tierValue !== null) {
          // 获取段位名称
          tierName = getTierName(tierValue);
          // 根据段位名称查找分数
          tierScore = SCORE_MAP[tierName as keyof typeof SCORE_MAP] || 0;
        }
        
        // 总分 = 段位分 + 比赛分
        const totalScore = tierScore + matchScoreTotal;
        
        return {
          id: player.id,
          name: player.name,
          avatar: player.avatar,
          region: player.region,
          score: totalScore,
          tier: tierValue,
          tierName: tierName // 添加段位名称
        };
      });
      
      // 按分数降序排序
      rankings.sort((a, b) => b.score - a.score);
      
      return NextResponse.json(rankings);
    } 
    // 否则返回总排行
    else {
      // 计算每个玩家的总分
      const rankings = players.map(player => {
        // 1. 计算比赛得分
        const matchScoreTotal = player.scores.reduce((sum, score) => {
          const scoreValue = score.value;
          return sum + scoreValue;
        }, 0);
        
        // 2. 计算段位得分
        const tierScoreTotal = calculateTierScore(player);
        
        // 3. 总分 = 比赛分 + 段位分
        const totalScore = matchScoreTotal + tierScoreTotal;
        
        // 4. 找出玩家的最高段位(数值最小的段位)
        const tierValues = [
          player.swordTier,
          player.crystalTier,
          player.buhcTier,
          player.potionTier,
          player.npotTier,
          player.smpTier
        ].filter(value => value !== null && value !== undefined) as number[];
        
        const bestTierValue = tierValues.length > 0 ? Math.min(...tierValues) : null;
        const bestTierName = getTierName(bestTierValue);
        
        // 5. 找出最高段位对应的游戏模式
        let bestTierMode = '';
        if (bestTierValue !== null) {
          const modes = ['SWORD', 'CRYSTAL', 'BUHC', 'POTION', 'NPOT', 'SMP'];
          const modeMapping = {
            'SWORD': player.swordTier,
            'CRYSTAL': player.crystalTier,
            'BUHC': player.buhcTier,
            'POTION': player.potionTier,
            'NPOT': player.npotTier,
            'SMP': player.smpTier
          };
          
          for (const mode of modes) {
            if (modeMapping[mode as keyof typeof modeMapping] === bestTierValue) {
              bestTierMode = mode;
              break;
            }
          }
        }
        
        return {
          id: player.id,
          name: player.name,
          avatar: player.avatar,
          region: player.region,
          score: totalScore,
          // 所有段位
          swordTier: player.swordTier,
          crystalTier: player.crystalTier,
          buhcTier: player.buhcTier,
          potionTier: player.potionTier,
          npotTier: player.npotTier,
          smpTier: player.smpTier,
          // 最高段位信息
          bestTier: bestTierValue,
          bestTierName: bestTierName,
          bestTierMode: bestTierMode,
          // 段位名称
          swordTierName: getTierName(player.swordTier),
          crystalTierName: getTierName(player.crystalTier),
          buhcTierName: getTierName(player.buhcTier),
          potionTierName: getTierName(player.potionTier),
          npotTierName: getTierName(player.npotTier),
          smpTierName: getTierName(player.smpTier)
        };
      });
      
      // 按分数降序排序
      rankings.sort((a, b) => b.score - a.score);
      
      return NextResponse.json(rankings);
    }
  } catch (error) {
    console.error('Rankings error:', error);
    return NextResponse.json(
      { error: '获取排行榜失败' },
      { status: 500 }
    );
  }
} 